package com.jky.trial.controller;


import com.jky.trial.common.BaseResult;
import com.jky.trial.common.Constants;
import com.jky.trial.service.FileService;
import com.jky.trial.util.Base64Util;
import com.jky.trial.util.ImageUtil;
import com.jky.trial.util.ImgUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * ref:http://www.iteye.com/topic/264457
 */
@RestController
@RequestMapping("/api/v1/")
//@Controller("/api/v1/")
public class CutImageController {

    FileService fileService;

    @Autowired
    CutImageController(FileService fileService) {
        this.fileService = fileService;
    }

    @RequestMapping(value = "/cutimage", method = RequestMethod.POST)
    public
    @ResponseBody
    BaseResult cutImage(@RequestParam("image") MultipartFile file, HttpServletRequest request) throws IOException {
        if (file.isEmpty()) {
            return new BaseResult(false, "file is empty", 400);
        }
        int x = Integer.valueOf(request.getParameter("x"));
        int y = Integer.valueOf(request.getParameter("y"));
        int width = Integer.valueOf(request.getParameter("width"));
        int height = Integer.valueOf(request.getParameter("height"));
        if (width == 0 || height == 0) {
            return new BaseResult(false, "parameters error", 400);
        }
        //nginx访问路径
        String webPath = Constants.nginxVisitUrl;
        //图片保存路径
        String imgPath = Constants.thumbnailPath;
        String fileName = UUID.randomUUID().toString().replaceAll("-", "");
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());

        File imgBig = new File(imgPath + fileName + "_big." + extension);
        file.transferTo(imgBig);

        File imgSmall = new File(imgPath + fileName + "_small." + extension);
        imgSmall.createNewFile();

        ImageUtil.cutImage(imgBig, new FileOutputStream(imgSmall), x, y, width, height);

        return new BaseResult(true, webPath + fileName + "_small." + extension, 200);
    }

    @RequestMapping(value = "/path-cut-image", method = RequestMethod.POST)
    @ResponseBody
    public BaseResult pathCutImage(HttpServletRequest request) throws IOException {

        int x = Integer.valueOf(request.getParameter("x"));
        int y = Integer.valueOf(request.getParameter("y"));
        int width = Integer.valueOf(request.getParameter("w"));
        int height = Integer.valueOf(request.getParameter("h"));
        String path = String.valueOf(request.getParameter("path"));
        if (width == 0 || height == 0 || path == null) {
            return new BaseResult(false, "parameters error", 400);
        }
        String webPath = Constants.nginxVisitUrl;
        String imgPath = Constants.thumbnailPath;
        path = path.replace(webPath, imgPath);

        File imgBig = new File(path);
        String small = path.replace("_f.", "_c.");
        System.out.println(small);
        File imgSmall = new File(small);
        imgSmall.createNewFile();

        ImageUtil.cutImage(imgBig, new FileOutputStream(imgSmall), x, y, width, height);
        Map map = new HashMap();
        small = small.replace(imgPath, webPath);
        map.put("path", small);
        return new BaseResult(true, map);
    }

    @ResponseBody
    @RequestMapping(value = "/pages/error/maxUploadExceeded", method = RequestMethod.GET)
    public BaseResult handleMaxUploadSizeExceededException(Exception ex, HttpServletRequest request) {
        if (ex instanceof org.springframework.web.multipart.MaxUploadSizeExceededException) {
            return new BaseResult(false, "最大上传文件不能超过5M!", 403);
        }
        return new BaseResult(false, "服务端错误!", 500);
    }

    /***
     * @param file
     * @param type 文件类型：默认图片，papaer合同
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public BaseResult upload(
            @RequestParam("file") MultipartFile file,
            Integer from,
            Integer folderId,
            String type,
            HttpServletRequest request,
            HttpServletResponse response
    ) throws IOException {
        if (file.isEmpty()) {
            return new BaseResult(false, "file is empty", 400);
        }
        response.setHeader("Content-type", "text/html");
        //图片保存路径
        String imgPath = "";
        String webPath = Constants.nginxVisitUrl;
        if ("paper".equals(type)) {
            imgPath = Constants.filePath;
        } else {
            imgPath = Constants.thumbnailPath;
        }

        String extension = FilenameUtils.getExtension(file.getOriginalFilename()); // 后缀
        String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "_f." + extension; // 新文件名
        String monthPath = getDayPath(); //
        String diskPath = imgPath + monthPath;
        File path = new File(diskPath);
        webPath += monthPath;
        if (!path.exists()) {
            path.mkdir(); //
        }
        File imgBig = new File(diskPath + fileName);
        String url = webPath + fileName;
        file.transferTo(imgBig);
        com.jky.trial.entity.File file1 = fileService.saveFileInfo(file.getOriginalFilename(),
                null, null,
                from != null ? from : Integer.valueOf(2), //默认后台
                type!=null?Integer.valueOf(type):0,
                url, extension,
                diskPath + fileName, file.getSize(), folderId == null ? 0 : folderId);

        Map map = new HashMap();
        map.put("path", url);
        map.put("currentFileName", file.getOriginalFilename());
        map.put("fileId", file1.getId());
        map.put("currentFileSize", fileName + "." + extension);
        map.put("currentWidth", fileName + "." + extension);
        map.put("status", true);

        return new BaseResult(true, map);
    }


    public String getDayPath() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        String datePath = sdf.format(date) + "/";
        return datePath;
    }

    @RequestMapping(value = "/path-cut-image-oss", method = RequestMethod.POST)
    @ResponseBody
    public BaseResult pathCutImageOss(HttpServletRequest request, String fileId, String mark, String degree) throws IOException {
        //http://image-demo.oss-cn-hangzhou.aliyuncs.com/example.jpg?x-oss-process=image/crop,x_100,y_50,w_100,h_100
        int x = Integer.valueOf(request.getParameter("x"));
        int y = Integer.valueOf(request.getParameter("y"));
        int width = Integer.valueOf(request.getParameter("w"));
        int height = Integer.valueOf(request.getParameter("h"));
        String path = String.valueOf(request.getParameter("path"));
        if (width == 0 || height == 0 || path == null) {
            return new BaseResult(false, "parameters error", 400);
        }
        path += (path.indexOf("x-oss-process=image") > -1 ? "," : ("?x-oss-process=image/")) + "crop,x_" + x + ",y_" + y + ",w_" + width + ",h_" + height;

        if (mark != null) { // 增加水印
            path += (path.indexOf("x-oss-process=image") > -1 ? "/" : ("?x-oss-process=image/")) + "watermark,type_d3F5LXplbmhlaQ,text_" + URLEncoder.encode(Base64Util.encodeStr(mark)) + ",color_FF0000,size_16,rotate_330";
        }
        Map map = new HashMap();
        if (StringUtils.isNoneBlank(fileId)) {
            com.jky.trial.entity.File file = new com.jky.trial.entity.File();
            file.setId(Integer.valueOf(fileId));
            file.setUrl(path);
            fileService.update(file);
        }
        map.put("path", path);

        return new BaseResult(true, map);
    }


    @RequestMapping(value = "/401", method = RequestMethod.GET)
    @ResponseBody
    public BaseResult m401() {
        return new BaseResult(false, "未登录", 401);
    }


}
